package cn.edu.sgu.www.mhxysy.service.exp.impl;

import cn.edu.sgu.www.mhxysy.pager.Pager;
import cn.edu.sgu.www.mhxysy.dto.exp.RoleExpDTO;
import cn.edu.sgu.www.mhxysy.entity.exp.RoleExp;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.mapper.exp.RoleExpMapper;
import cn.edu.sgu.www.mhxysy.pager.exp.RoleExpPager;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import cn.edu.sgu.www.mhxysy.service.exp.RoleExpService;
import cn.edu.sgu.www.mhxysy.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class RoleExpServiceImpl implements RoleExpService {

    private final RoleExpMapper roleExpMapper;

    @Autowired
    public RoleExpServiceImpl(RoleExpMapper roleExpMapper) {
        this.roleExpMapper = roleExpMapper;
    }

    @Override
    public void insert(RoleExpDTO roleExpDTO) {
        RoleExp roleExp = selectByRoleId(roleExpDTO.getRoleId());

        if (roleExp == null) {
            roleExp = toEntity(roleExpDTO);
            
            roleExp.setId(roleExp.uuid());

            roleExpMapper.insert(roleExp);
        } else {
            throw new GlobalException(ResponseCode.BAD_REQUEST, "角色经验已存在。");
        }
    }

    @Override
    public void deleteById(String id) {
        roleExpMapper.deleteById(id);
    }

    @Override
    public void updateById(RoleExpDTO roleExpDTO) {
        if (StringUtils.isNullOrEmpty(roleExpDTO.getId())) {
            throw new GlobalException(ResponseCode.BAD_REQUEST, "角色经验ID不能为空！");
        }

        RoleExp roleExp = toEntity(roleExpDTO);

        roleExpMapper.updateById(roleExp);
    }

    @Override
    public RoleExp selectByRoleId(String roleId) {
        QueryWrapper<RoleExp> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("role_id", roleId);

        return roleExpMapper.selectOne(queryWrapper);
    }

    @Override
    public Page<RoleExp> selectByPage(RoleExpPager pager) {
        QueryWrapper<RoleExp> queryWrapper = new QueryWrapper<>();
        Page<RoleExp> page = Pager.ofPage(pager);

        queryWrapper.eq(
                StringUtils.isNotEmpty(pager.getRoleId()),
                "role_id", pager.getRoleId()
        );

        return roleExpMapper.selectPage(page, queryWrapper);
    }

    private RoleExp toEntity(RoleExpDTO roleExpDTO) {
        RoleExp roleExp = new RoleExp();

        roleExp.setId(roleExpDTO.getId());
        roleExp.setExp(roleExpDTO.getExp());
        roleExp.setYfjy(roleExpDTO.getYfjy());
        roleExp.setTotal(roleExpDTO.getTotal());
        roleExp.setRoleId(roleExpDTO.getRoleId());

        return roleExp;
    }

}